package com.group.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.view.BaseResult;
import com.base.view.GeneralResult;
import com.group.model.*;
import com.group.util.NoteException;

/**
 * 脑力相关接口
 * 
 * @author zhaolei
 *
 */
@Controller
public class BrainController extends BaseController {

	Map<Long, BrainGame> games = new HashMap<>();

	/**
	 * 获取用户游戏次数
	 * 
	 * @param request HttpServletRequest
	 * @return Integer
	 */
	@GetMapping("/brain/user/times")
	@ResponseBody
	public GeneralResult<Integer> getUserTimes(HttpServletRequest request) {
		User user = getUser(request);
		int freeTime = getTimes(user);

		return new GeneralResult<Integer>().setValue(freeTime);
	}

	private int getTimes(User user) {
		String date = df.format(new Date());
		Long userId = user.getId();

		// 计算玩的次数
		int playedTimes = userDao.countBrainGames(userId, date);
		// 计算分享次数
		int shareTimes = userDao.countBrainShare(userId, date);
		if (shareTimes > 0)
			shareTimes = 2;

		int freeTime = 3 + shareTimes - playedTimes;
		if (freeTime < 0)
			freeTime = 0;

		return freeTime;
	}

	/**
	 * 开始游戏
	 * 
	 * @param type
	 *            0 芬果答题 , 1另一个答题
	 * @param request HttpServletRequest
	 * @return BrainGame
	 * @throws InterruptedException InterruptedException
	 */
	@GetMapping("/brain/start")
	@ResponseBody
	public GeneralResult<BrainGame> start(Integer type, HttpServletRequest request) throws InterruptedException {
		User user = getUser(request);

		if (getTimes(user) == 0) {
			throw new NoteException("答题次数已经用光");
		}

		if (type == null)
			type = 0;

		// User user = beanDao.quickQueryOneById(User.class, 1l);
		BrainGame bg = new BrainGame();
		bg.setUser1(user);
		bg.setState(0);
		if (type == 0)
			bg.setQuestions(userDao.getBrainQuestions());
		else
			bg.setQuestions(userDao.getBrainQuestions1());
		// 添加机器人
		User user2 = userDao.getRandomUser();
		BrainRobot robot = new BrainRobot();
		robot.setName(user2.getName());
		robot.setHeadimage(user2.getHeadimage());
		robot.initRandom();
		bg.setUser2(robot);
		bg.setId(user.getId());
		games.put(bg.getId(), bg);
		Thread t = new Thread(bg);
		t.start();

		return new GeneralResult<BrainGame>().setValue(bg);
	}

	/**
	 * 答题
	 * 
	 * @param answer 回答
	 * @param request 请求
	 * @return BaseResult
	 */
	@GetMapping("/brain/answer")
	@ResponseBody
	public BaseResult answer(String answer, HttpServletRequest request) {
		User user = getUser(request);

		// User user = beanDao.quickQueryOneById(User.class, 1l);
		BrainGame game = games.get(user.getId());
		game.setAnswer1(answer);

		return new BaseResult();
	}

	/**
	 * 查询当前游戏状态(轮询查询,建议建个1秒左右)
	 * 
	 * @param gameId 游戏id
	 * @return BrainGame
	 */
	@GetMapping("/brain/game/id")
	@ResponseBody
	public GeneralResult<BrainGame> getGame(Long gameId) {

		return new GeneralResult<BrainGame>().setValue(games.get(gameId));
	}

	/**
	 * 获取游戏结果
	 * 
	 * @param gameId 游戏id
	 * @return Double
	 */
	@GetMapping("/brain/game/result")
	@ResponseBody
	public GeneralResult<Double> getGameResult(Long gameId) {
		BrainGame bg = games.get(gameId);

		if (bg.getState() != 100) {
			throw new NoteException("游戏未结束");
		}
		// 结束进程
		bg.setFlag(false);

		// 删除map
		games.remove(gameId);

		// 保存结果
		BrainResult result = new BrainResult();
		result.setDate(df.format(new Date()));
		result.setUserId(bg.getUser1().getId());
		result.setResult("失败");

		Double bonus = 0d;
		// 结算币
		if (bg.getScore1() > bg.getScore2()) {
			int winTimes = userDao.countWinBrainGames(result.getUserId(), df.format(new Date()));
			// bonus = getSystemParaValueDouble("gameBonus");
			if (winTimes == 0) {
				bonus = 3d;
			} else if (winTimes == 1) {
				bonus = 2d;
			} else if (winTimes == 2) {
				bonus = 3d;
			} else if (winTimes == 3) {
				bonus = 2d;
			} else if (winTimes == 4) {
				bonus = 4d;
			}

			tickerService.addTicker(bg.getUser1().getId(), "wecc", bonus, "游戏奖励", null);
			result.setResult("胜利");
		}

		beanDao.save(result);

		return new GeneralResult<Double>().setValue(bonus);
	}

	/**
	 * 分享游戏
	 * @param request HttpServletRequest
	 * @return BaseResult
	 */
	@GetMapping("/brain/game/share")
	@ResponseBody
	public BaseResult shareGame(HttpServletRequest request) {
		User user = getUser(request);

		BrainGameShare bgs = new BrainGameShare();
		bgs.setUserId(user.getId());
		bgs.setDate(df.format(new Date()));
		beanDao.save(bgs);

		return new BaseResult();
	}

}
